// services/api/upload.ts
import { http } from '@/lib/request'
import type { UploadResponse, FileCourseInfo } from '../types'

export const uploadService = {
  // 上传/编辑教程
  /*
  {
	"category_sign": "imageToText",
	"type": "video",
	"title": "教程",
	"content": "教程链接地址",
    "id":1
}
  */
  uploadCourseFile: async (
    file: File,
    data: {
      category_sign: 'imageToText' | 'videoCreation'
      // type: string
      // title: string
      // content: string
      // id: number
    },
    onProgress?: (progress: number) => void,
  ) => {
    const uploadInfo = await uploadService.uploadFile(file, onProgress)

    return await http.post<FileCourseInfo>('/course/store', {
      id: uploadInfo.id,
      content: uploadInfo.url, // 上传成功后返回的url
      title: uploadInfo.name, // 上传成功后返回的name
      type: uploadInfo.exts, // 上传成功后返回的ext
      category_sign: data.category_sign,
    })
  },
  // 上传单个文件
  uploadFile: async (file: File, onProgress?: (progress: number) => void) => {
    return http.upload<UploadResponse>('/upload', file, (progressEvent) => {
      if (onProgress) {
        const progress = Math.round(
          (progressEvent.loaded * 100) / progressEvent.total,
        )
        onProgress(progress)
      }
    })
  },

  // 上传多个文件
  uploadMultipleFiles: async (
    files: File[],
    onProgress?: (fileIndex: number, progress: number) => void,
  ) => {
    const uploads = files.map((file, index) =>
      http.upload<UploadResponse>('/upload', file, (progressEvent) => {
        if (onProgress) {
          const progress = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total,
          )
          onProgress(index, progress)
        }
      }),
    )

    return Promise.all(uploads)
  },
}
